import { ref } from "vue";
// 导入日期处理库
import moment from "moment";
// 导入发表评论接口
import { publishComment } from "@/api/forumAPI";
import { message } from "ant-design-vue";

export const usePublishComment = (
  getCommentData,
  current,
  pagesize,
  commentTotal
) => {
  // 发表内容
  const commentValue = ref("");

  // 发表状态
  const submitting = ref(false);

  // 点击发表
  const handleSubmit = (forumId, userInfos) => {
    if (!commentValue.value) {
      return;
    }

    // 发表状态
    submitting.value = true;
    // 参数
    const params = {
      forum_id: forumId,
      user_id: userInfos.id,
      username: userInfos.username,
      avatar: userInfos.avatar,
      content: commentValue.value,
      createtime: moment().format("YYYY-MM-DD HH:mm:ss"),
    };
    // 发送请求发表评论
    publishComment(params)
      .then((res) => {
        submitting.value = false;
        if (res.status === 200) {
          commentValue.value = "";
          message.success(res.msg);
          // 如果有总数
          if (commentTotal.value) {
            // 总数模每页数量能模尽就让页码+1
            if (commentTotal.value % pagesize.value === 0) {
              current.value =
                Math.ceil(commentTotal.value / pagesize.value) + 1;
            } else {
              current.value = Math.ceil(commentTotal.value / pagesize.value);
            }
          }
          // 重新渲染数据
          getCommentData();
        }
      })
      .catch((error) => {
        throw new Error(error);
      });
  };

  return {
    commentValue,
    submitting,
    handleSubmit,
  };
};
